package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.PermissionService;
import cn.wolfcode.service.RoleService;
import cn.wolfcode.vo.JsonResult;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 角色处理器
 *
 * @author 杨兴健
 * @Date 2020/7/9 10:30
 */
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService service;

    @Autowired
    private PermissionService permissionService;

    /**
     * 查询所有角色
     *
     * @param qo
     * @param model
     * @return
     */
    @RequestMapping("/list")
    @RequiresPermissions(value = {"role:list", "角色列表"}, logical = Logical.OR)
    public String list(@ModelAttribute("qo") QueryObject qo, Model model) {

        model.addAttribute("pageInfo", service.selectAllByQO(qo));
        return "/role/list";
    }

    /**
     * 跳转更新|添加页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/input")
    @RequiresPermissions(value = {"role:input", "角色更新|添加页面"}, logical = Logical.OR)
    public String input(Long id, Model model) {
        if (id != null) {
            Role role = service.selectById(id);
            model.addAttribute("role", role);
        }
        List<Permission> permissions = permissionService.selectAll();
        model.addAttribute("permissions", permissions);
        return "role/input";
    }

    /**
     * 更新|添加
     *
     * @param role
     * @param pids
     * @return
     */
    @RequestMapping("/saveOrUpdate")
    @RequiresPermissions(value = {"role:saveOrUpdate", "角色更新|添加"}, logical = Logical.OR)
    @ResponseBody
    public JsonResult saveOrUpdate(Role role, Long[] pids) {

        service.saveOrUpdate(role, pids);

        return new JsonResult(true, "操作成功！");
    }

    /**
     * 根据id删除角色
     *
     * @param id
     * @return
     */
    @RequiresPermissions(value = {"role:delete", "角色删除"}, logical = Logical.OR)
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {

        service.delete(id);

        return new JsonResult(true, "删除成功！");
    }


}
